package com.itheima.exception;

import com.itheima.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/*
 全局异常处理器类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    //捕获指定异常 处理  java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'zhangsan' for key 'idx_username'
    //你要捕获什么异常 进行处理  在这个注解中就写什么异常类型
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        if(ex.getMessage().contains("Duplicate entry")){
            //得到异常错误信息
            String message = ex.getMessage();
            String[] split = message.split(" ");
            return R.error(split[2]+"已存在");
        }
        return R.error("未知异常！");
    }

    //捕获 自定义异常进行处理
    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandler(CustomException ex){
        return R.error(ex.getMessage());
    }


}
